package com.yudi.blog.bussiness.service.impl;

import com.yudi.blog.bussiness.dao.TagsRepository;
import com.yudi.blog.bussiness.dto.Tag;
import com.yudi.blog.bussiness.service.TagService;
import com.yudi.blog.exception.NotFoundException;
import com.yudi.blog.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * @Author YuDi
 * @Date 2021/11/10 21:19
 * @Version 1.0
 */
@Service
public class TagsServiceImpl implements TagService {

    @Autowired
    private TagsRepository tagsRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Tag saveTag(Tag tag) {
        return tagsRepository.save(tag);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteTag(Long id) {
        tagsRepository.deleteById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Tag getTag(Long id) {
        return tagsRepository.getById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagsRepository.getById(id);
        if(t == null){
            throw  new NotFoundException("不存在该类标签");
        }
        BeanUtils.copyProperties(tag, t);
        return tagsRepository.save(t);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagsRepository.findAll(pageable);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Tag> listTag() {
        return tagsRepository.findAll();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Tag> listTag(String ids) {
        return tagsRepository.findAllById(listTagsId(ids));
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
        Pageable pageable = PageRequest.of(0, size, sort);

        return tagsRepository.findTop(pageable);
    }


    private List<Long> listTagsId(String ids){
        List<Long> ans = new ArrayList<>();

        if(!StringUtils.isEmpty(ids)){
            String[] arr = ids.split(",");
            for(int i = 0; i < arr.length; i++){
                ans.add(new Long(arr[i]));
            }
        }
        return ans;
    }


}
